<?php

namespace App\Services;

use App\HelpTutorial;
use App\HelpTutorialImage;
use App\UploadedFileState;
use App\Lib\Util\QueryPager;
use DB;

class HelpTutorialService
{
    private function baseQuery()
    {
        return HelpTutorial::select('id', 'title', 'content', 'sort_order', 'parent_id');
    }

    public function getHelpTutorials(Array $input, $paging = true)
    {
        $query = $this->baseQuery();

        if (!empty($input['parentId'])) {
            $query = $query->where('parent_id', $input['parentId']);
        } else if ($input['parentId'] === 0) {
            $query = $query->whereNull('parent_id');
        }

        $pager = new QueryPager($query);

        $pager->setRefectionMethodField('fullPath');

        return $paging ? $pager->doPaginate($input, 'sort_order') :
            $pager->queryWithoutPaginate($input, 'sort_order');
    }

    public function getHelpTutorialImages(Array $input, $paging = true)
    {
        $query = HelpTutorialImage::where('tutorial_id', $input['tutorial_id']);

        $pager = new QueryPager($query);

        $pager->setRefectionMethodField('getFullImagePath');

        return $paging ? $pager->doPaginate($input, 'id') :
            $pager->queryWithoutPaginate($input, 'id');
    }

    public function getPossiableParentTutorials($parent)
    {
        if (isset($parent)) {
            if (!empty($parent->parent_id)) {
                return HelpTutorial::where('parent_id', $parent->parent_id)
                    ->orderBy('sort_order')->get();
            }
        }

        return HelpTutorial::whereNull('parent_id')
            ->orderBy('sort_order')->get();
    }

    public function getCascadeTutorials($defaultTutorial=null)
    {
        $allTutorials = HelpTutorial::select('id', 'title as name', 'parent_id')
            ->orderBy('sort_order')->get()->toArray();

        $allChildTutorials = $this->getChildTutorials($allTutorials, $defaultTutorial);

        if (isset($defaultTutorial)) {
            array_push($allChildTutorials, $defaultTutorial);
        }

        return $allChildTutorials;
    }

    public function getTutorialImages($tutorialId)
    {
        return HelpTutorialImage::where('tutorial_id', $tutorialId)->get();
    }

    public function deleteTutorialImage($tutorialImageId)
    {
        return HelpTutorialImage::where('id', $tutorialImageId)->delete();
    }

    public function addTutorialImage($tutorialId, $imageId)
    {
        HelpTutorialImage::create([
            'tutorial_id' => $tutorialId,
            'file_id' => $imageId
        ]);
    }

    public function getPossiableParentTutorialsExceptSelf($tutorialId)
    {
        $tutorials = HelpTutorial::all();
        $countTutorials = count($tutorials);
        for ($i=0; $i<$countTutorials; $i++) {
            if ($tutorials[$i]->id == $tutorialId) {
                unset($tutorials[$i]);
                break;
            }
        }

        return $tutorials;
    }

    public function saveNewTutorial($tutorial, $detailImages, $guidField)
    {
        DB::transaction(function () use ($tutorial, $detailImages, $guidField) {
            $tutorialId = HelpTutorial::create([
                'title' => $tutorial['title'],
                'content' => $tutorial['content'],
                'parent_id' => !empty($tutorial['parent_id'])?$tutorial['parent_id']:null,
                'sort_order' => $tutorial['sort_order'],
            ])->id;

            $detailImage = explode(',', $detailImages);

            foreach ($detailImage as $imageItem) {
                $file = UploadedFileState::select('file_id as id')->where('state', 0)->where('batch_upload_origin_name', $imageItem)
                    ->where('guid', $guidField)->first();

                if (isset($file)) {
                    HelpTutorialImage::create([
                        'tutorial_id' => $tutorialId,
                        'file_id' => $file->id
                    ]);

                    UploadedFileState::where('state', 0)->where('batch_upload_origin_name', $imageItem)->where('guid', $guidField)
                        ->update([
                            'batch_upload_origin_name' => null,
                            'guid' => null,
                            'state' => 1
                        ]);
                }
            }
        });
    }

    private function getChildTutorials($allTutorials, $parentTutorial)
    {
        $children = [];

        $tutorialCount = count($allTutorials);

        for ($i=0; $i<$tutorialCount; $i++) {
            $tutorial = $allTutorials[$i];

            if  ($parentTutorial === null) {
                if (empty($tutorial['parent_id'])) {
                    $currentTutorial = $tutorial;
                    array_push($children, $currentTutorial);
                    unset($allTutorials[$i]);
                }
            } else {
                if ($tutorial['parent_id'] == $parentTutorial['id']) {
                    $currentTutorial = $tutorial;
                    array_push($children, $currentTutorial);
                    unset($allTutorials[$i]);
                }
            }
        }

        $result = [];

        $childrenCount = count($children);
        if ($childrenCount > 0) {
            $allTutorials = array_values($allTutorials);

            for ($i=0; $i<$childrenCount; $i++) {
                $currentTutorial = $children[$i];

                array_push($result, array_merge($currentTutorial, [
                    'spread' => true,
                    'children' => $this->getChildTutorials($allTutorials, $currentTutorial)
                ]));
            }
        }

        return $result;
    }

    public function hasChildren($tutorialId)
    {
        return HelpTutorial::where('parent_id', $tutorialId)->count() > 0;
    }
}
